﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text;
using UnityEditor;
using Framework;


namespace FrameworkEditor
{
    /// <summary>
    /// 生成modules目录下文件的汇总lua文件
    /// </summary>
    public class GenLuaModules
    {
        private static string _modulesPath = "Assets/"+ FrameworkSettings.ProjDirName + "/Scripts/Lua/modules";
        private static string _moudlesSearchPath = "Assets/"+ FrameworkSettings.ProjDirName + "/Scripts/Lua/";
        private static string _moudlesSettingsPath = _modulesPath + "/settings/";
        private static string _moudlesRequireLuaPtah = _moudlesSettingsPath + "/require_modules.lua";

        private static string _frameworkPath = "Assets/framework/Scripts/Lua/framework";
        private static string _frameworkSearchPath = "Assets/framework/Scripts/Lua";
        private static string _frameworkRequireLuaPath = _frameworkPath + "/require_framework.lua";

        public static void GenModules()
        {
            Debug.Log("start gen modules require file... ");
            GenLogicModules();
            Debug.Log("end gen modules require file... ");
        }

        //[MenuItem("SLTools/Lua/Gen modules require file")]
        public static void GenLogicModules()
        {
            if (!FileHelper.IsDirExists(_modulesPath))
            {
                return;
            }

            AssetDatabase.Refresh();

            System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
            strBuilder.AppendLine("-- this file is auto gen, dot not modify by yourself ...");

            foreach (string file in Directory.GetFiles(_modulesPath, "*.lua", SearchOption.AllDirectories))
            {
                string assetPath = EditorUtils.GetRelativePathToDir(file, _moudlesSearchPath).Replace(".lua", "");
                string luaPath = assetPath.Replace("/", ".");
                if (luaPath.StartsWith("modules.setting.") || luaPath.StartsWith("modules.proto."))
                {
                    continue;
                }

                string[] splitArr = luaPath.Split('.');
                string moduleName = splitArr[splitArr.Length - 1];
                //Debug.Log($"asetPath = {assetPath} luaPath = {luaPath} moduleName = {moduleName}");
                strBuilder.AppendLine($"setNeedLoadModule(\"{luaPath}\", \"{moduleName}\")");

                CheckFileContentModuleEqual(file, luaPath);
            }

            string content = strBuilder.ToString();
            Debug.Log(content);
            FileHelper.WriteTextToPath(_moudlesRequireLuaPtah, content);
            AssetDatabase.Refresh();
        }

        private static void CheckFileContentModuleEqual(string fileName, string luaPath)
        {
            StreamReader sr = new StreamReader(fileName, Encoding.UTF8);
            string line;
            sr.BaseStream.Seek(0, SeekOrigin.Begin);
            int lineIdx = 0;
            while ((line = sr.ReadLine()) != null)
            {
                if (line.IndexOf("module(", StringComparison.Ordinal) >= 0)
                {
                    var sp = line.Split('"');
                    if (sp.Length > 1 && sp[1] != luaPath)
                    {
                        Framework.Logger.LogError("lua path not match:   " + sp[1] + "  =>  " + luaPath);
                    }
                    break;
                }
                if (lineIdx++ > 10) break;
            }
            sr.Close();
        }

        public static void GenFramework()
        {
            if (!FileHelper.IsDirExists(_frameworkPath))
            {
                return;
            }

            AssetDatabase.Refresh();

            System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
            strBuilder.AppendLine("-- this file is auto gen, dot not modify by yourself ...");

            foreach (string file in Directory.GetFiles(_frameworkPath, "*.lua", SearchOption.AllDirectories))
            {
                string assetPath = EditorUtils.GetRelativePathToDir(file, _frameworkSearchPath).Replace(".lua", "");
                string luaPath = assetPath.Replace("/", ".");
                if (luaPath.StartsWith("framework.core."))
                {
                    continue;
                }

                if (luaPath.Equals("framework.require_framework"))
                {
                    strBuilder.AppendLine($"addGlobalModule(\"framework.core.require_framework_core\")");
                    continue;
                }

                string[] splitArr = luaPath.Split('.');
                string moduleName = splitArr[splitArr.Length - 1];
                //Debug.Log($"asetPath = {assetPath} luaPath = {luaPath} moduleName = {moduleName}");
                strBuilder.AppendLine($"setNeedLoadModule(\"{luaPath}\", \"{moduleName}\")");
                CheckFileContentModuleEqual(file, luaPath);
            }

            string content = strBuilder.ToString();
            Debug.Log(content);
            FileHelper.WriteTextToPath(_frameworkRequireLuaPath, content);
            AssetDatabase.Refresh();
        }
    }
}